<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天页面</title>
    <!-- 引入 Vue -->
    <script src="./node_modules/vue/dist/vue.js"></script>
    <!-- 引入 Element UI -->
    <link rel="stylesheet" href="./node_modules/element-ui/lib/theme-chalk/index.css">
    <script src="./node_modules/element-ui/lib/index.js"></script>
    <!-- 引入axios -->
    <script src="./node_modules/axios/dist/axios.js"></script>
    <!-- 引入 CSS -->
    <link rel="stylesheet" href="css/chat-client.css">
</head>
<body>
    <div id="app">
        <el-card>
            <h2>聊天页面</h2>
            <div class="communication-status" v-if="isConnected">
                正在与 {{ userId }} 沟通中
            </div>
        </el-card>
        <div class="chat-container" v-if="isConnected">
            <div class="chat-log">
                <div v-for="(message, index) in chatLog" :key="index" :class="['message', message.type]">
                    <div class="message-bubble" v-html="message.content"></div>
                </div>
            </div>
            <div class="chat-input">
                <el-input v-model="chatMessage" placeholder="请输入消息" @keyup.enter.native="sendMessage"></el-input>
                <el-button type="primary" @click="sendMessage">发送</el-button>
            </div>
        </div>
    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    userId: localStorage.getItem('userId'),
                    isConnected: true,
                    chatLog: [], // 聊天记录
                    chatMessage: '', // 当前输入的消息
                    eventSource: null, // SSE 连接
                    currentMessage: '', // 当前累积的消息
                    isFirstMessage: true // 标志是否是第一条消息
                };
            },
            methods: {
                sendMessage() {
                    if (this.chatMessage.trim() !== '') {
                        this.chatLog.push({
                            type: 'user-message',
                            content: `我: ${this.chatMessage}`
                        });
                        axios.post('http://127.0.0.1:8080/ai/chat/doctor', {
                            currentUserName: this.userId,
                            message: this.chatMessage
                        })
                        .then(response => {
                            console.log('发送消息成功:', response.data);
                            this.eventSource = new EventSource(`http://localhost:8080/sse/connect?userId=${this.userId}`);
                            this.eventSource.onmessage = (event) => {
                                console.log('接收到 SSE 数据:', event.data);
                                this.handleSSEMessage(event.data);
                            };
                            this.eventSource.onclose = () => {
                                console.log('SSE 连接关闭');
                            };
                        })
                        .catch(error => {
                            console.error('发送消息失败:', error);
                        });
                        this.chatMessage = '';
                    }
                },
                handleSSEMessage(data) {
                    if (data === 'finish') {
                        if (this.currentMessage) {
                            this.chatLog.push({
                                type: 'ai-message',
                                content: `AI: ${this.currentMessage}`
                            });
                            this.currentMessage = '';
                        }
                        if (this.eventSource) {
                            this.eventSource.close();
                            this.eventSource = null;
                        }
                        this.isFirstMessage = true;
                        return;
                    }
                    if (data.startsWith('<think>') && data.endsWith('</think>')) {
                        if (this.currentMessage) {
                            this.chatLog.push({
                                type: 'ai-message',
                                content: `AI: ${this.currentMessage}`
                            });
                            this.currentMessage = '';
                        }
                        this.chatLog.push({
                            type: 'ai-message',
                            content: `<span class="think">${data}</span>`
                        });
                    } else {
                        if (this.isFirstMessage) {
                            this.chatLog.push({
                                type: 'ai-message',
                                content: `AI: ${data}`
                            });
                            this.isFirstMessage = false;
                        } else {
                            this.chatLog.push({
                                type: 'ai-message',
                                content: data
                            });
                        }
                    }
                }
            }
        });
    </script>
</body>
</html>